package com.itfreer.file.path;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import com.itfreer.file.FileSegmentInfo;

/**
 * 定义对象上传接口
 */
public class FileUpload extends BasePath {

	/**
	 * 单一实例
	 */
	public static final FileUpload instance = new FileUpload();

	private FileUpload(){

	}

    /**
     * 获取文件
     * @param bucketName
     * @param objectName
     * @return
     */
	public String getFile(String bucketName, String objectName) {
		if(bucketName==null || bucketName.trim().equals("")
				|| objectName==null || objectName.trim().equals("")){
			return null;
		}

		String path = getBasePath();
		if (!objectName.endsWith("/")) {
			objectName += "/";
		}
		if (path.endsWith("/")) {
			path += bucketName + "/";
		} else {
			path += "/" + bucketName + "/";
		}
		path += objectName;
        if (path.endsWith("/")) {
            path = path.substring(0, path.length()-1);
        }
		return path;
	}

    /**
     * 获取文件夹路径
     *
     * @param bucketName
     *            存储块名称
     * @param objectName
     *            文件夹名称
     */
    public String getDir(String bucketName, String objectName) {
        if(bucketName==null || bucketName.trim().equals("")
                || objectName==null || objectName.trim().equals("")){
            return null;
        }

        String path = getBasePath();
        if (!objectName.endsWith("/")) {
            objectName += "/";
        }
        if (path.endsWith("/")) {
            path += bucketName + "/";
        } else {
            path += "/" + bucketName + "/";
        }
        path += objectName;

        String[] paths = path.split("/");
        String newPath = "";
        for(int i=0;i<paths.length;i++){
            if(i==paths.length-1){
                if(paths[i].contains(".")){
                    newPath = newPath.substring(0,newPath.length()-1);
                }else{
                    newPath += paths[i];
                }
            }else{
                newPath += paths[i] + "/";
            }
        }

        return newPath;
    }

	/**
	 * 创建文件夹
	 * 多级目录创建最后一级即可，比如dir1/dir2/dir3/，创建dir1/dir2/dir3/即可，dir1/、dir1/dir2/不需要创建
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectName
	 *            文件夹名称
	 */
	public void createDir(String bucketName, String objectName) {
	    if(bucketName==null || bucketName.trim().equals("")
                || objectName==null || objectName.trim().equals("")){
	        return;
        }

        String path = getBasePath();
        if (!objectName.endsWith("/")) {
            objectName += "/";
        }
        if (path.endsWith("/")) {
            path += bucketName + "/";
        } else {
            path += "/" + bucketName + "/";
        }
        path += objectName;

        String[] paths = path.split("/");
        String newPath = "";
        for(int i=0;i<paths.length;i++){
            if(i==paths.length-1){
                if(paths[i].contains(".")){
                    newPath = newPath.substring(0,newPath.length()-1);
                }else{
                    newPath += paths[i];
                }
            }else{
                newPath += paths[i] + "/";
            }
        }


		File fileinfo = new File(newPath);
		if (!fileinfo.isDirectory()) {
			fileinfo.mkdirs();
		}
	}

	/**
	 * 上传文件流
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象存储key
	 * @param content
	 *            对象流
	 * @return 文件是否上传成功
	 */
	public boolean putObject(String bucketName, String objectKey, byte[] content) {
        createDir(bucketName, objectKey);
		String fileName = getBasePath();
		if (fileName.endsWith("/")) {
			fileName += bucketName + "/";
		} else {
			fileName += "/" + bucketName + "/";
		}
		fileName += objectKey;
		try {
			FileOutputStream file = new FileOutputStream(fileName);
			file.write(content);
			file.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 断点续传上传
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象存储key
	 * @param part
	 *            文件块
	 */
	public boolean uploadFile(String bucketName, String objectKey, FileSegmentInfo part) {
        createDir(bucketName, objectKey);
		String fileName = getBasePath();
		if (fileName.endsWith("/")) {
			fileName += bucketName + "/";
		} else {
			fileName += "/" + bucketName + "/";
		}
		fileName += objectKey;
		
		try {
			RandomAccessFile fileOutputStream = new RandomAccessFile(fileName, "rwd");
			Long start = part.getSegmentIndex() * part.getSegmentSize();
			fileOutputStream.seek(start);
			fileOutputStream.write(part.getSegmentContent(), 0, part.getSegmentContent().length);
			fileOutputStream.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
